package com.wnn.demo.model.hospital.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wnn.demo.advice.MyException;
import com.wnn.demo.domain.Employee;
import com.wnn.demo.model.hospital.mapper.EmployeeMapper;
import com.wnn.demo.model.hospital.mapper.HospitalMapper;
import com.wnn.demo.pojo.ResultCode;
import com.wnn.demo.utils.IdWorker;
import com.wnn.demo.utils.MyStringUtil;
import com.wnn.demo.utils.redis.RedisManager;
import com.wnn.demo.vo.EmployeeJobs;
import com.wnn.demo.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Array;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HospitalMapper hospitalMapper;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private IdWorker idWorker;

    public static String employeeRegisterCountKey = "today:employee:register:count:";

    /**
     * 查找所有员工信息
     * @param page
     * @param limit
     * @return
     */
    public PageInfo< EmployeeVo >  selectEmployeeList(String searchEmployee,String employeeIdView,String isCheck
                                                    ,String hId, String pId , String deptChildId,Integer type,Integer page, Integer limit) {
        //查找所有员工的工作信息
        List<Map<String,Object>> employeeAllJobList = employeeMapper.selectEmployeeJobInfo();
        //封装map  key为员工id，value为list 每一行为该员工的一份工作
        HashMap<String, Object> logEmployeeMap = new HashMap<>();
        for (Map m:employeeAllJobList) {
            String employeeId = (String) m.get("employeeId");
            //先判断 logEmployeeMap 容器中是否已经存在 该用户K,V信息
            List<Map<String,Object>>   isHave = ( List<Map<String,Object>> ) logEmployeeMap.get(employeeId);
            //不存在 创建value数据
            if (isHave==null){
                ArrayList<Map> employeeHaveInfoList = new ArrayList<>();
                employeeHaveInfoList.add(m);
                logEmployeeMap.put(employeeId,employeeHaveInfoList);
            }else {
                //存在  通过员工id找到list 再添加job信息
                ArrayList<Map>  employeeHaveInfoList = (ArrayList<Map>) logEmployeeMap.get(employeeId);
                employeeHaveInfoList.add(m);
            }
        }
        PageHelper.startPage(page,limit);
        List<EmployeeVo> employeeList = employeeMapper.selectEmployeeList(searchEmployee,hId,deptChildId,employeeIdView,isCheck);
        // 给每个员工包装类封装jobs属性
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String nowSystemTime = sdf.format( System.currentTimeMillis());
        for (EmployeeVo e:employeeList) {
            String employeeId = e.getEmployeeId();
            //根据出生日期填写转化成当前年龄
            if (e.getBirthday()!=null){
                e.setAge(this.getAgeByBirth( nowSystemTime, sdf.format(e.getBirthday()) ) );
            }
            List<Map<String,Object>> employeeInfoList = ( List<Map<String,Object>>) logEmployeeMap.get(employeeId);
            ArrayList<EmployeeJobs> employeeJobs = new ArrayList<>();
            for (Map<String,Object> jobMapInfo:employeeInfoList) {
                if( !MyStringUtil.isNullOrEmpty((String) jobMapInfo.get("hdeId"))){
                    EmployeeJobs employeeJob = new EmployeeJobs();
                    employeeJob.setHdeId( (String) jobMapInfo.get("hdeId"));
                    employeeJob.setHdId( (String) jobMapInfo.get("hdId"));
                    employeeJob.setEmployeeId( (String) jobMapInfo.get("employeeId"));
                    employeeJob.setPJobId((Integer) jobMapInfo.get("jobParentId") );
                    employeeJob.setJobId((Integer) jobMapInfo.get("jobId") );
                    employeeJob.setHospitalId( (String) jobMapInfo.get("hospitalid"));
                    employeeJob.setDeptId( (String) jobMapInfo.get("deptid"));
                    employeeJobs.add(employeeJob);
                }
            }
            e.setJobs(employeeJobs);
        }
        return new PageInfo<>(employeeList);
    }

    /**
     * 新增员工
     * @param employeeVo
     * @return
     */
    @Transient
    public int insertEmployee(EmployeeVo employeeVo) {
        // 1、数据校验 姓名、手机号 不为空
        if (MyStringUtil.isNullOrEmpty(employeeVo.getEmployeeName())){
            throw new MyException(ResultCode.NULL,"员工姓名不能为空！");
        }
        if (MyStringUtil.isNullOrEmpty(employeeVo.getPhone())){
            throw new MyException(ResultCode.NULL,"员工电话号码不能为空！");
        }

        // 2、数据校验 工号、手机号、邮箱、身份证号 的唯一性
        // 检查工号
        if (!MyStringUtil.isNullOrEmpty(employeeVo.getEmployeeNumber())){
            Example exampleNumber = new Example(Employee.class);
            exampleNumber.createCriteria().andEqualTo("employeeNumber", employeeVo.getEmployeeNumber());
            List<Employee> employeeNumberList = employeeMapper.selectByExample(exampleNumber);
            if (!employeeNumberList.isEmpty()){
                throw new MyException(ResultCode.NULL,"员工工号[" + employeeVo.getEmployeeNumber() +"]重复！可不填写，系统自动分配！" );
            }
        }
        // 检查手机号
        Example examplePhone = new Example(Employee.class);
        examplePhone.createCriteria().andEqualTo("phone", employeeVo.getPhone());
        List<Employee> examplePhoneList = employeeMapper.selectByExample(examplePhone);
        if (!examplePhoneList.isEmpty()){
            throw new MyException(ResultCode.NULL,"员工电话号码[" + employeeVo.getPhone() +"]重复" );
        }
        // 检查邮箱
        if (!MyStringUtil.isNullOrEmpty(employeeVo.getMailbox())) {
            Example exampleEmail = new Example(Employee.class);
            exampleEmail.createCriteria().andEqualTo("mailbox", employeeVo.getMailbox());
            List<Employee> exampleEmailList = employeeMapper.selectByExample(exampleEmail);
            if (!exampleEmailList.isEmpty()) {
                throw new MyException(ResultCode.NULL, "员工邮箱信息[" + employeeVo.getMailbox() + "]重复");
            }
        }
        // 检查身份证号
        if (!MyStringUtil.isNullOrEmpty(employeeVo.getIdentityCard())){
            Example exampleIdentityCard = new Example(Employee.class);
            exampleIdentityCard.createCriteria().andEqualTo("identityCard", employeeVo.getIdentityCard());
            List<Employee> exampleIdentityCardList = employeeMapper.selectByExample(exampleIdentityCard);
            if (!exampleIdentityCardList.isEmpty()){
                throw new MyException(ResultCode.NULL,"员工身份证号信息[" + employeeVo.getIdentityCard() +"]重复" );
            }
        }

        String id = idWorker.nextId() + "";
        // 获取一个Date对象
        java.util.Date date = new java.util.Date();
        Timestamp timeStamp = new Timestamp(date.getTime());
        //默认工号实现
//        String strDate = new SimpleDateFormat("yyyyMMdd").format(date);
//        String employeeNumber = strDate.substring(2, 8);
//        //从redis获取当天录入员工的号数
//        AtomicInteger registerCount = (AtomicInteger)redisManager.get(employeeRegisterCountKey);
//        if (registerCount==null){
//            registerCount = new AtomicInteger(1);
//            redisManager.set( employeeRegisterCountKey, registerCount,MyStringUtil.getRemainderSeconds());
//        }
//        int i = registerCount.incrementAndGet();
//        String lastStr = String.valueOf(i);
//        for (int j = 0; j < 4-lastStr.length(); j++) {
//            employeeNumber = employeeNumber +  "0" ;
//        }
//        employeeNumber += lastStr;
//        redisManager.set( employeeRegisterCountKey, registerCount);

        employeeVo.setEmployeeId(id);
        employeeVo.setCreateTime(timeStamp);
//        employeeVo.setEmployeeNumber(employeeNumber);
        int resultRow = employeeMapper.insert(employeeVo);

        //多职位处理
        List<EmployeeJobs> employeeHaveJobList = employeeVo.getJobs();
        ArrayList<EmployeeJobs> addEmployeeJobList = new ArrayList<>();
        if (employeeHaveJobList!=null){
            HashMap<String, String> hdInfoMap = this.getHospAndDeptMapInfo();
            for (EmployeeJobs jobsInfo:employeeHaveJobList
            ) {
                String hdId = hdInfoMap.get(jobsInfo.getHospitalId() + jobsInfo.getDeptId());
                if (MyStringUtil.isNullOrEmpty(hdId)){
                    continue;
                }
                jobsInfo.setHdId(hdId);
                jobsInfo.setEmployeeId(employeeVo.getEmployeeId());
                //通过判断 hd_employee 表中的主键 hdeId 判断该职位新增还是更新
                String hdeId = jobsInfo.getHdeId();
                if (MyStringUtil.isNullOrEmpty(hdeId)){
                    jobsInfo.setHdeId(idWorker.nextId() + "");
                    //如果为空新增
                    addEmployeeJobList.add(jobsInfo);
                }
            }
        }
        if (!addEmployeeJobList.isEmpty()){
            employeeMapper.insertEmployeeJobList(addEmployeeJobList);
        }
        return  resultRow;

    }

    /**
     * 更新员工
     * @return
     */
    @Transient
    public int updateEmployee(EmployeeVo employeeVo) {
        // 1、数据校验 工号、手机号、邮箱、身份证号 的唯一性
        // 检查工号
        if (!MyStringUtil.isNullOrEmpty(employeeVo.getEmployeeNumber())){
            Example exampleNumber = new Example(Employee.class);
            exampleNumber.createCriteria().andEqualTo("employeeNumber", employeeVo.getEmployeeNumber())
                                                     .andNotEqualTo("employeeId",employeeVo.getEmployeeId());
            List<Employee> employeeNumberList = employeeMapper.selectByExample(exampleNumber);
            if (!employeeNumberList.isEmpty()){
                throw new MyException(ResultCode.NULL,"员工工号[" + employeeVo.getEmployeeNumber() +"]重复！可不填写，系统自动分配！" );
            }
        }
        // 检查手机号
        Example examplePhone = new Example(Employee.class);
        examplePhone.createCriteria().andEqualTo("phone", employeeVo.getPhone())
                                                    .andNotEqualTo("employeeId",employeeVo.getEmployeeId());
        List<Employee> examplePhoneList = employeeMapper.selectByExample(examplePhone);
        if (!examplePhoneList.isEmpty()){
            throw new MyException(ResultCode.NULL,"员工电话号码[" + employeeVo.getPhone() +"]重复" );
        }
        // 检查邮箱
        if (!MyStringUtil.isNullOrEmpty(employeeVo.getMailbox())) {
            Example exampleEmail = new Example(Employee.class);
            exampleEmail.createCriteria().andEqualTo("mailbox", employeeVo.getMailbox())
                                                        .andNotEqualTo("employeeId",employeeVo.getEmployeeId());
            List<Employee> exampleEmailList = employeeMapper.selectByExample(exampleEmail);
            if (!exampleEmailList.isEmpty()) {
                throw new MyException(ResultCode.NULL, "员工邮箱信息[" + employeeVo.getMailbox() + "]重复");
            }
        }
        // 检查身份证号
        if (!MyStringUtil.isNullOrEmpty(employeeVo.getIdentityCard())){
            Example exampleIdentityCard = new Example(Employee.class);
            exampleIdentityCard.createCriteria().andEqualTo("identityCard", employeeVo.getIdentityCard())
                                                            .andNotEqualTo("employeeId",employeeVo.getEmployeeId());
            List<Employee> exampleIdentityCardList = employeeMapper.selectByExample(exampleIdentityCard);
            if (!exampleIdentityCardList.isEmpty()){
                throw new MyException(ResultCode.NULL,"员工身份证号信息[" + employeeVo.getIdentityCard() +"]重复" );
            }
        }

        //多职位处理
        List<EmployeeJobs> employeeHaveJobList = employeeVo.getJobs();
        ArrayList<EmployeeJobs> addEmployeeJobList = new ArrayList<>();
        ArrayList<EmployeeJobs> updateEmployeeJobList = new ArrayList<>();
        if (employeeHaveJobList!=null){
            HashMap<String, String> hdInfoMap = this.getHospAndDeptMapInfo();
            for (EmployeeJobs jobsInfo:employeeHaveJobList
            ) {
                String hdId = hdInfoMap.get(jobsInfo.getHospitalId() + jobsInfo.getDeptId());
                if (MyStringUtil.isNullOrEmpty(hdId)){
                    continue;
                }
                jobsInfo.setHdId(hdId);
                jobsInfo.setEmployeeId(employeeVo.getEmployeeId());
                //通过判断 hd_employee 表中的主键 hdeId 判断该职位新增还是更新
                String hdeId = jobsInfo.getHdeId();
                if (MyStringUtil.isNullOrEmpty(hdeId)){
                    jobsInfo.setHdeId(idWorker.nextId() + "");
                    //如果为空新增
                    addEmployeeJobList.add(jobsInfo);

                }else {
                    //如果不为空更新
                    updateEmployeeJobList.add(jobsInfo);
                }
            }
        }
        Example example = new Example(Employee.class);
        example.createCriteria().andEqualTo("employeeId", employeeVo.getEmployeeId());
        if (!addEmployeeJobList.isEmpty()){
            employeeMapper.insertEmployeeJobList(addEmployeeJobList);
        }
        if (!updateEmployeeJobList.isEmpty()){
            employeeMapper.updateEmployeeJobList(updateEmployeeJobList);
        }
        if (employeeVo.getDeleteHdeIds()!=null){
            employeeMapper.btachDeleteEmployeeJobList(employeeVo.getEmployeeId(),employeeVo.getDeleteHdeIds());
        }
        return employeeMapper.updateByExampleSelective(employeeVo,example);

    }

    /**
     * 删除一个员工
     * @param id
     * @return
     */
    public int deleteEmployeeById(String id) {
        return employeeMapper.deleteByPrimaryKey(id);
    }

    /**
     * 批量删除员工
     * @param ids
     * @return
     */
    public int batchEmployeeByIds(String ids) {
        return employeeMapper.deleteByIds(ids);
    }

    /**
     * 查找员工个人信息
     * @param username
     * @return
     */
    public Map< String, Object > findEmployeeInfo(String username) {
        return employeeMapper.findEmployeeInfo(username);
    }


    /**
     * 手写批量删除范例
     * @param ids
     * @return
     */
    public int testBatchEmployeeByIds(String ids) {

        List< String > keys = Arrays.asList(ids.split(","));
        System.out.println(keys);
        return  employeeMapper.testBatchEmployeeByIds(keys);

    }

    public List<Map<String,Object>> findHospitalAndDept(String hId, Integer type, String pDeptId) {
        List<Map<String,Object>> list = employeeMapper.findHospitalAndDept(hId,type,pDeptId);
        return list;
    }

    /**
     *  返回 组装中间表医院信息 hosp_dept
     */
    private HashMap<String, String> getHospAndDeptMapInfo() {
        List<Map<String,String>> hdInfoList = employeeMapper.selectHospDeptList();
        HashMap<String, String> hdInfoMap = new HashMap<>();
        for (Map<String,String> m:hdInfoList
        ) {
            String key = m.get("hospitalid") + m.get("deptid");
            hdInfoMap.put(key ,m.get("hdId"));
        }
        return hdInfoMap;
    }




    /**
     * 根据出生年月计算年龄
     * @param nowDate
     * @param birth
     * @return age
     */
    private  Integer getAgeByBirth(String nowDate ,String birth) {
        if ("".equals(birth.trim()) || birth.trim() == null) {
            return null;
        }
        //此处调用了获取当前日期，以yyyy-MM-dd格式返回的日期字符串方法
        return Integer.parseInt(nowDate.substring(0, 4))- Integer.parseInt(birth.substring(0,4));
    }
}
